﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Xml;
using EnvDTE;

namespace RuleCode.ObjectTree
{
    public partial class DataBaseConfig : Form
    {
        private bool onlyNew = false;
        public bool OnlyNew
        {
            set {
                onlyNew = value;
            }
            get {
                return onlyNew;
            }
        }

        /// <summary>
        /// 获取或设置插件宿主对象
        /// </summary>
        public DTE AddIn_ApplicationObject
        {
            get;
            set;
        }

        private string connectStringID=string.Empty ;
        /// <summary>
        /// 获取 连接字符串在配置文件中的GUID类型的ID
        /// </summary>
        public string ConnectStringID
        {
            get { return connectStringID; }
        }

        /// <summary>
        /// 获取 判断是否是新建数据库
        /// </summary>
        private bool IsNewDataBase
        {
            get {
                return CheckBox_New.Checked;
            }
        }

        public DataBaseConfig()
        {
            InitializeComponent();
        }

        #region 方式
        private void CheckBox_New_CheckedChanged(object sender, EventArgs e)
        {
            bool isNew = CheckBox_New.Checked;    
            CheckBox_UserOld .Checked = !isNew;
            TabControl_Main.TabPages.Clear();
            TabControl_Main.TabPages.Add(isNew ? TabPage_New : TabPage_UseOld);  

        }

        private void CheckBox_UserOld_CheckedChanged(object sender, EventArgs e)
        {
            bool isOld = CheckBox_UserOld.Checked;
            CheckBox_New.Checked = !isOld;
            TabControl_Main.TabPages.Clear();
            TabControl_Main.TabPages.Add(isOld ?TabPage_UseOld:TabPage_New );
        }
        #endregion

        #region 页面加载
        private void DataBaseConfig_Load(object sender, EventArgs e)
        {
            if (onlyNew)
            {
                CheckBox_New.Checked = true;
                CheckBox_New.Enabled = false;
                CheckBox_CreateAllTables.Checked = true;
                CheckBox_CreateAllTables.Enabled = false;
                CheckBox_UserOld.Visible = false;                            
            }
            else
            {
                CheckBox_New.Checked = false;
            }
            CheckBox_New_CheckedChanged(CheckBox_New, EventArgs.Empty);

            InitTabPage_New();
            InitTabPage_UserOld();
        }
        #endregion

        #region 取消保存按钮
        private void Button_Cancel_Click(object sender, EventArgs e)
        {
            connectStringID = string.Empty;
            this.Close();
        }

        private void Button_TestConnect_Click(object sender, EventArgs e)
        {
            string connectionString = string.Empty;
            if (CheckBox_New.Checked)
            {
                SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

                 
                if (this.RadioButton_WindowLogin.Checked)
                {
                    connectionStringBuilder.IntegratedSecurity = true;
                }
                else if (this.RadioButton_SQLServer.Checked)
                {
                    connectionStringBuilder.IntegratedSecurity = false;
                    connectionStringBuilder.UserID = this.TextBox_UserID.Text;
                    connectionStringBuilder.Password = this.TextBox_Password.Text;
                }

                connectionStringBuilder.InitialCatalog = "master";
                connectionString = connectionStringBuilder.ToString();                  
            }
            else
            {
                connectionString = this.ListBox_CurrentCNNStrList.Text;
            }

            try
            {
                SqlConnection cnn = new SqlConnection(connectionString);
                if (cnn != null)
                {
                    MessageBox.Show("连接成功！");
                    return;
                }
            }
            catch
            {
                MessageBox.Show("连接失败！");
            }
        }
        #endregion

        #region 辅助方法
        private void InitCurrentCNNStrList()
        {
            try
            {
                DataTable dTable = new DataTable();
                dTable.Columns.Add("ID");
                dTable.Columns.Add("Value");
                ListBox_CurrentCNNStrList.Items.Clear();
                ListBox_CurrentCNNStrList.ValueMember = "ID";
                ListBox_CurrentCNNStrList.DisplayMember = "Value";
                XmlDocument profileXmlDoc = new XmlDocument();
                profileXmlDoc.Load(Util.GetProfilePath());
                XmlNodeList xmlNodes = profileXmlDoc.SelectNodes("//cnnString");
                foreach (XmlNode node in xmlNodes)
                {
                    try
                    {
                        string Id = node.Attributes.GetNamedItem("ID").Value;
                        string cnnStr = node.Attributes.GetNamedItem("Value").Value;
                        dTable.Rows.Add(new object[] { Id, cnnStr });
                    }
                    catch { }
                }
                ListBox_CurrentCNNStrList.DataSource = dTable;
                if (ListBox_CurrentCNNStrList.Items.Count > 0)
                {
                    ListBox_CurrentCNNStrList.SelectedIndex = 0;
                    ListBox_CurrentCNNStrList_SelectedIndexChanged(ListBox_CurrentCNNStrList, EventArgs.Empty);
                }
            }
            catch (Exception error)
            {
                Util.SetStatusInfo(error.Message);
            }
        }

        /// <summary>
        /// 初始化 使用原有数据库 Tab页
        /// </summary>
        private void InitTabPage_UserOld()
        {
            InitCurrentCNNStrList();
        }

        /// <summary>
        /// 初始化 新建数据库 Tab页
        /// </summary>
        private void InitTabPage_New()
        {
            TextBox_DataBase_Source.Text = "Microsoft SQL Server (SqlClient)";
            //InitDBServerComboBox();
            InitTabPage_New_Other(false );  
        }

        private void InitTabPage_New_Other(bool selectedHost)
        {
            if (!selectedHost)
            {
                TextBox_Password.ReadOnly = true;
                TextBox_UserID.ReadOnly = true;
                RadioButton_WindowLogin.Checked = true;
                RadioButton_SQLServer.Checked = false;
            }
            CheckBox_CoverOldDB.Enabled = selectedHost;
            TextBox_NewDBName.ReadOnly = !selectedHost;
            ListBox_OldDBs.Enabled = selectedHost;
            ListBox_OldDBs.BackColor =selectedHost?SystemColors.ActiveCaptionText : SystemColors.Control;
        }

        private void ValidateConnectStr()
        { 
        }

        private void InitDBServerComboBox()
        {
            this.ComboBox_Host.Items.Clear();
            DataTable sqlDataTable = SqlDataSourceEnumerator.Instance.GetDataSources();
            if (sqlDataTable != null)
            {
                foreach (DataRow dRow in sqlDataTable.Rows)
                {
                    this.ComboBox_Host .Items.Add(dRow["ServerName"].ToString());
                }
            }
        }

        /// <summary>
        /// 更新现有数据库信息
        /// </summary>
        private void UpdateOldDbList()
        {
            this.ListBox_OldDBs.Items.Clear();
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            if (ComboBox_Host.Text != "")
                connectionStringBuilder.DataSource = ComboBox_Host.Text;
            else
                return;

            if (this.RadioButton_WindowLogin.Checked)
            {
                connectionStringBuilder.IntegratedSecurity = true;
            }
            else if (this.RadioButton_SQLServer.Checked)
            {
                connectionStringBuilder.IntegratedSecurity = false;
                connectionStringBuilder.UserID = this.TextBox_UserID.Text;
                connectionStringBuilder.Password = this.TextBox_Password.Text;
            }

            connectionStringBuilder.InitialCatalog = "master";

            string connectionString = connectionStringBuilder.ToString();
            SqlConnection cnn=null;
            try
            {
                cnn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("Select * from dbo.sysdatabases", cnn);
                SqlDataReader rdr;
                if (cnn.State != ConnectionState.Open)
                    cnn.Open();
                rdr = cmd.ExecuteReader();

                if (rdr != null)
                {
                    while (rdr.Read())
                    {
                        this.ListBox_OldDBs.Items.Add(rdr["name"].ToString());
                    }
                }
                rdr.Close();
            }
            catch
            {
                if(cnn!=null)
                    cnn.Close();
                return;
            }
            finally
            {

            }
        }
        #endregion

        #region TabPage_New
        private void Button_RefreshHost_Click(object sender, EventArgs e)
        {
            InitDBServerComboBox();
        }


        private void RadioButton_WindowLogin_CheckedChanged(object sender, EventArgs e)
        {
            TextBox_Password.ReadOnly = true;
            TextBox_UserID.ReadOnly = true;
        }

        private void RadioButton_SQLServer_CheckedChanged(object sender, EventArgs e)
        {
            TextBox_UserID.ReadOnly = false;
            TextBox_Password.ReadOnly = false;
        }

        private void ComboBox_Host_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool hasSelected = this.ComboBox_Host.Text.Trim ()!=string.Empty ;
            InitTabPage_New_Other(hasSelected);

        }
        #endregion


        #region TabPage_Old
        private void ListBox_CurrentCNNStrList_SelectedIndexChanged(object sender, EventArgs e)
        {
            TextBox_SelectedCurrentCNNStr.Text = this.ListBox_CurrentCNNStrList.Text.ToString();   
        }
        #endregion

        private void ComboBox_Host_Validated(object sender, EventArgs e)
        {
            this.ListBox_OldDBs.Items.Clear();

            bool hasSelected = this.ComboBox_Host.Text.Trim() != string.Empty;
            InitTabPage_New_Other(hasSelected);
            UpdateOldDbList();
            
        }

        private void Button_UpdateDBList_Click(object sender, EventArgs e)
        {
            UpdateOldDbList();
        }

        private void Button_NewDB_Click(object sender, EventArgs e)
        {

            if (TextBox_NewDBName.Text.Trim() == string.Empty)
            {
                MessageBox.Show("请输入新建数据库的名称！");
                return;
            }

            string dbName = TextBox_NewDBName.Text;
            for (int i = 0; i < ListBox_OldDBs.Items.Count; i++)
            {
                if (dbName == ListBox_OldDBs.Items[i].ToString())
                {
                    if (MessageBox.Show("您要新建的数据库已经存在，是否要覆盖！") == DialogResult.OK)
                    {
                        CheckBox_CoverOldDB.Checked = true;
                    }
                    else
                    {
                        return;
                    }
                    break;
                }
            }

            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();

            if (ComboBox_Host.Text != "")
                connectionStringBuilder.DataSource = ComboBox_Host.Text;
            else
                return;

            if (this.RadioButton_WindowLogin.Checked)
            {
                connectionStringBuilder.IntegratedSecurity = true;
            }
            else if (this.RadioButton_SQLServer.Checked)
            {
                connectionStringBuilder.IntegratedSecurity = false;
                connectionStringBuilder.UserID = this.TextBox_UserID.Text;
                connectionStringBuilder.Password = this.TextBox_Password.Text;
            }

            connectionStringBuilder.InitialCatalog = "master";
            string cnnStr = connectionStringBuilder.ConnectionString;
            SqlHelper.Instance.CreatDataBase(dbName, CheckBox_CoverOldDB.Checked, false, cnnStr);


            try
            {
                connectionStringBuilder.InitialCatalog = dbName;
                cnnStr = connectionStringBuilder.ConnectionString;

                //修改profile文件
                string profileName = Util.GetProfilePath();
                XmlDocument profileDoc = new XmlDocument();
                profileDoc.Load(profileName);
                XmlNode cnnStrsNode = profileDoc.SelectSingleNode("//cnnStrings");
                if (cnnStrsNode != null)
                {
                    XmlNode cnnStrNode = profileDoc.CreateElement("cnnString");
                    XmlAttribute idAttr = profileDoc.CreateAttribute("ID");
                    idAttr.Value = Guid.NewGuid().ToString("N");
                    cnnStrNode.Attributes.Append(idAttr);
                    XmlAttribute valueAttr = profileDoc.CreateAttribute("Value");
                    valueAttr.Value = cnnStr;
                    cnnStrNode.Attributes.Append(valueAttr);
                    cnnStrsNode.AppendChild(cnnStrNode);

                    //设置 连接字符串的ID
                    connectStringID = idAttr.Value;   
                    //执行新建数据库所需要的所有脚本
                    Util.ExecNewDataBaseScript(cnnStr,CheckBox_CreateAllTables .Checked );


                    profileDoc.Save(profileName);
                    MessageBox.Show("新建数据库成功！");
                    this.Close();

                }
            }
            catch(Exception error) {
                MessageBox.Show("新建数据库失败！");
                Util.SetStatusInfo(error .Message );
            }
        }

        private void Button_SelectCurrentCNN_Click(object sender, EventArgs e)
        {
            connectStringID = this.ListBox_CurrentCNNStrList.SelectedValue.ToString();
            this.Close();
        }

        private void ComboBox_Host_DropDown(object sender, EventArgs e)
        {
            if (ComboBox_Host.Items.Count <= 0)
                InitDBServerComboBox();
        }

        private void ListBox_CurrentCNNStrList_DoubleClick(object sender, EventArgs e)
        {
            connectStringID = this.ListBox_CurrentCNNStrList.SelectedValue.ToString();
            this.Close();
        }

        

    }
}
